package com.tin.triper.UI;

import java.io.File;
import java.util.Date;

import com.tin.triper.Constants;
import com.tin.triper.R;
import com.tin.triper.Data.LocationProvider;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ImageActivity extends Activity {
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;

	EditText editTextField;
	TextView textViewField;
	ImageView image;
	Button buttonTakePhoto;
	Button buttonOK;
	Button buttonCancel;
	String fileName = "";
	SharedPreferences prefs;
	boolean photoTaken = false;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		prefs = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);

		if (getIntent().getExtras().getInt(Constants.ACTIVITY_MODE) == 0) {
			// add
			setContentView(R.layout.image_add);
			editTextField = (EditText) findViewById(R.id.image_add_description_field);
			buttonOK = (Button) findViewById(R.id.image_add_button_ok);
			buttonCancel = (Button) findViewById(R.id.image_add_button_cancel);
			buttonTakePhoto = (Button) findViewById(R.id.image_take_photo);
			image = (ImageView) findViewById(R.id.image_add_photo);
			image.setVisibility(View.GONE);
			Date date = new Date();
			fileName = "Image_" + date.getTime() + ".jpg";
			buttonOK.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					if (!editTextField.getText().toString().equals("")
							&& photoTaken) {
						ContentValues values = new ContentValues();
						values.put(LocationProvider.RESOURCE_FILENAME, fileName);
						values.put(LocationProvider.RESOURCE_TYPE, 2);// TODO
																		// add
																		// enum
						values.put(LocationProvider.RESOURCE_DESCRIPTION,
								editTextField.getText().toString());
						values.put(LocationProvider.TRIP_ID,
								prefs.getInt(Constants.RECORDED_TRIP_ID, 0));
						values.put(LocationProvider.LOCATION_ID,
								prefs.getInt(Constants.LAST_INSERTED_LOCATION_ID, 0));
						getContentResolver().insert(
								LocationProvider.CONTENT_URI_RESOURCES, values);
						finish();
					} else {
						if(photoTaken){
							Toast.makeText(
									ImageActivity.this,
									getString(R.string.error_message_no_image),
									Toast.LENGTH_SHORT).show();
						}
						if(editTextField.getText().toString().equals("")){
							Toast.makeText(
									ImageActivity.this,
									getString(R.string.error_message_no_description),
									Toast.LENGTH_SHORT).show();
						}
						
					}
				}
			});
			buttonTakePhoto.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

					File mediaStorageDir = new File(Environment
							.getExternalStorageDirectory().getAbsolutePath()
							+ "/"
							+ Constants.APP_FOLDER_NAME
							+ "/"
							+ prefs.getInt(Constants.RECORDED_TRIP_ID, 0)
							+ " "
							+ prefs.getString(Constants.RECRODED_TRIP_NAME, "")
							+ "/Image/");
					if (!mediaStorageDir.exists()) {
						if (!mediaStorageDir.mkdirs()) {
							return;
						}
					}
					File mediaFile = new File(mediaStorageDir.getPath(),
							fileName);
					intent.putExtra(MediaStore.EXTRA_OUTPUT,
							Uri.fromFile(mediaFile));
					startActivityForResult(intent,
							CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

				}
			});
			buttonCancel.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					setResult(Constants.TEXT_ACTIVITY);
					finish();
				}
			});
		} else if (getIntent().getExtras().getInt(Constants.ACTIVITY_MODE) == 1) {
			// edit
			setContentView(R.layout.image_edit);
			editTextField = (EditText) findViewById(R.id.image_edit_description_field);
			buttonOK = (Button) findViewById(R.id.image_edit_button_ok);
			buttonCancel = (Button) findViewById(R.id.image_edit_button_cancel);
			image = (ImageView) findViewById(R.id.image_edit_photo);

			Cursor cursor = getContentResolver().query(
					LocationProvider.CONTENT_URI_RESOURCES,
					new String[] { LocationProvider.RESOURCE_DESCRIPTION,
							LocationProvider.RESOURCE_FILENAME },
					LocationProvider.RESOURCE_ID
							+ " ='"
							+ getIntent().getExtras().getInt(
									Constants.RESOURCE_ID) + "'", null, null);
			if (cursor != null)
				if (cursor.moveToFirst()) {
					editTextField.setText(cursor.getString(0));
					fileName = cursor.getString(1);
					File mediaStorageDir = new File(Environment
							.getExternalStorageDirectory().getAbsolutePath()
							+ "/"
							+ Constants.APP_FOLDER_NAME
							+ "/"
							+ getIntent().getExtras().getInt(Constants.TRIP_ID)
							+ " "
							+ getIntent().getExtras().getString(Constants.TRIP_NAME)
							+ "/Image/");
					File mediaFile = new File(mediaStorageDir.getPath(),
							fileName);
					image.setImageURI(Uri.fromFile(mediaFile));
				}
			cursor.close();
			buttonOK.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					if (!editTextField.getText().equals("")) {
						ContentValues values = new ContentValues();
						values.put(LocationProvider.RESOURCE_DESCRIPTION,
								editTextField.getText().toString());
						getContentResolver().update(
								LocationProvider.CONTENT_URI_RESOURCES,
								values,
								LocationProvider.RESOURCE_ID
										+ " ='"
										+ getIntent().getExtras().getInt(
												Constants.RESOURCE_ID) + "'",
								null);
						finish();
					} else {
						Toast.makeText(
								ImageActivity.this,
								getString(R.string.error_message_no_description),
								Toast.LENGTH_SHORT).show();
					}
				}
			});
			buttonCancel.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					finish();
				}
			});
		} else if (getIntent().getExtras().getInt(Constants.ACTIVITY_MODE) == 2) {
			setContentView(R.layout.image_view);
			textViewField = (TextView) findViewById(R.id.image_view_description_field);
			buttonOK = (Button) findViewById(R.id.image_view_button_ok);
			image = (ImageView) findViewById(R.id.image_view_photo);

			Cursor cursor = getContentResolver().query(
					LocationProvider.CONTENT_URI_RESOURCES,
					new String[] { LocationProvider.RESOURCE_DESCRIPTION,
							LocationProvider.RESOURCE_FILENAME },
					LocationProvider.RESOURCE_ID
							+ " ='"
							+ getIntent().getExtras().getInt(
									Constants.RESOURCE_ID) + "'", null, null);
			if (cursor != null)
				if (cursor.moveToFirst()) {
					textViewField.setText(cursor.getString(0));
					fileName = cursor.getString(1);
					File mediaStorageDir = new File(Environment
							.getExternalStorageDirectory().getAbsolutePath()
							+ "/"
							+ Constants.APP_FOLDER_NAME
							+ "/"
							+ getIntent().getExtras().getInt(Constants.TRIP_ID)
							+ " "
							+ getIntent().getExtras().getString(Constants.TRIP_NAME)
							+ "/Image/");
					File mediaFile = new File(mediaStorageDir.getPath(),
							fileName);
					image.setImageURI(Uri.fromFile(mediaFile));
				}
			cursor.close();
			buttonOK.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					finish();
				}
			});
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				photoTaken = true;
				buttonTakePhoto.setText(getString(R.string.image_retake_photo));
				image.setVisibility(View.VISIBLE);
				File mediaStorageDir = new File(Environment
						.getExternalStorageDirectory().getAbsolutePath()
						+ "/"
						+ Constants.APP_FOLDER_NAME
						+ "/"
						+ prefs.getInt(Constants.RECORDED_TRIP_ID, 0)
						+ " "
						+ prefs.getString(Constants.RECRODED_TRIP_NAME, "")
						+ "/Image/");
				File mediaFile = new File(mediaStorageDir.getPath(), fileName);
				image.setImageURI(Uri.fromFile(mediaFile));
			} else if (resultCode == RESULT_CANCELED) {
				photoTaken = false;
				image.setVisibility(View.GONE);
				buttonTakePhoto.setText(getString(R.string.image_take_photo));
			} else {
			}
		}

	}
}
